<script setup lang="ts">
import { pageTypeList } from "./components/config";
import SetTemplate from "./step/SetTemplate.vue";
import MyComponets from "./activityTemplate/MyComponets.vue";
import ImportComponentsDialog from "./activityTemplate/ImportComponentsDialog.vue";
import { deepClone, debounce, newRandomUid } from "@/utils";
import store from "@/store";

const props = defineProps({
  modelValue: {
    type: Array,
  },
  original: {
    type: String,
    default: "saas",
  },
});

const route = useRoute()

const updatePoster: any = inject("updatePoster");

const iframeLoading = ref(true),
  templateConfig = ref<Array<any>>([]),
  iframeReady = ref(false),
  templateReady = ref(false),
  currentPage = ref(""),
  // iframeUrl = (window as any).VUE_APP_URL[import.meta.env.MODE]
  //   .activePreviewPath + store.state.user.merchant.merchantCode,
  iframeUrl = window.VUE_APP_URL[import.meta.env.MODE].activePreviewPath + store.state.user?.merchant?.merchantCode,
  showAddPageDialog = ref(false),
  pageForm = ref<any>({}),
  importConfigDialog = ref(false),
  importConfigForm = ref<any>({ name: "", icon: "" });

const iframe = ref(),
  pageFormRef = ref(),
  templateRef = ref<Array<any>>([]),
  myComponentRef = ref();

const toUpdateIframeMessage = debounce(
  async () => {
    (iframe as any).value.contentWindow.postMessage(
      {
        method: "updateIframeMessage",
        pageName: currentPage.value,
        params: {
          pageConfig: deepClone(pageTemplate()),
        },
      },
      "*"
    );
  },
  300,
  false
);



const stop = watch(
  () => props.modelValue,
  (val) => {
    templateConfig.value = val || [];
    templateConfig.value.forEach((item) => {
      if (!item.uid) item.uid = newRandomUid();
      if (
        !item.configList.find((config: any) => config.type === "Background")
      ) {
        initPageConfig(item);
      }
    });
    currentPage.value = templateConfig.value[0].uid;
    templateReady.value = true;
    nextTick(() => {
      stop();
    });
  }
);

watch([templateReady, iframeReady], ([ready1, ready2]) => {
  if (ready1 && ready2) {
    iframeLoading.value = false;
    toUpdateIframeMessage();
  }
});

const currentComponentList = ref([] as any)

const from = computed(() => route.query.from)

// 组件选项卡数据
const componentList = computed(() => {
  currentComponentList.value = pageTypeList.find(
    (item: any) => item.pageType === currentPageType.value
  );
  return currentComponentList.value?.components || [];
});
// const componentList = computed({
//   get: () => {
//     //   let pageType: any = pageTypeList.find(
// //     (item: any) => item.pageType === currentPageType.value
// //   );
// //   return pageType?.components || [];
//   },
//   set: (val) => {

//   },
// });


// 当前tab索引
const tabIndex = computed(() => {
  let index = templateConfig.value.findIndex(
    (item) => item.uid === currentPage.value
  );
  return index;
});

// 当前页面类型
const currentPageType = computed(() => {
  let page = templateConfig.value.find(
    (item) => item.uid === currentPage.value
  );
  return page ? page.pageType : "";
});

// 自定义页面列表
const customPageList = computed(() => {
  return templateConfig.value.filter((item) => item.pageType === "CustomPage");
});

// 初始化页面
const initPageConfig = (config: any) => {
  nextTick(() => {
    addComponent({ name: "页面背景", type: "Background" }, {}, config.uid);
  });
};

// 添加组件
const addComponent = (component: any, config = {}, page?: string) => {
  console.log(component,"999");
  
  let { type, name, group } = component;
  if (config) { }
  if (!type) {
    ElMessage({
      message: "暂未上线该组件，敬请期待",
      type: "warning",
    });
    return;
  }
  // 指定页面
  let pageConfig = null;
  if (page) {
    pageConfig = templateConfig.value.find((item) => item.uid === page);
  } else
    pageConfig = templateConfig.value.find(
      (item) => item.uid === currentPage.value
    );

  // 裂变唯一
  if (type === "FissionBtn" || type === "TeamUp") {
    let templ = pageConfig.configList.find(
      (item: any) => item.type === "FissionBtn" || item.type === "TeamUp"
    );
    if (templ) {
      ElMessageBox.alert(
        `活动只支持一种裂变方式，请先删除【${templ.name}】后再尝试添加该组件`,
        "温馨提示",
        {
          confirmButtonText: "我知道了",
        }
      );
      return;
    }
  }
  // 投票唯一
  else if (type === "VoteOnly") {
    let templ = pageConfig.configList.find(
      (item: any) => item.type === "VoteOnly"
    );
    if (templ) {
      ElMessageBox.alert(`已存在投票活动`, "温馨提示", {
        confirmButtonText: "我知道了",
      });
      return;
    }
  }

  //自定义弹框
  if(component.type=='CustomPopup'){
    config.$autoShow=0
    config.$frequency=1
  }
  let uid = newRandomUid();
  pageConfig.configList.push({
    type,
    group,
    pageConfig: {},
    ...config,
    uid,
    name,
  });

  if (!page || page === currentPage.value) {
    templateRef.value[tabIndex.value].jumpTo(uid);
  }
  toUpdateIframeMessage();
};

const pageTemplate = () => {
  let page = templateConfig.value.find(
    (item) => item.uid === currentPage.value
  );
  if (page) return page.configList;
  return [];
};

// 新增自定义页面
const tabAdd = () => {
  pageForm.value = {};
  if (pageFormRef.value) pageFormRef.value.resetFields();
  showAddPageDialog.value = true;
};

// 编辑自定义页面
const editTab = (page: any) => {
  if (pageFormRef.value) pageFormRef.value.resetFields();
  pageForm.value.uid = page.uid;
  pageForm.value.pageName = page.pageName;
  showAddPageDialog.value = true;
};

// 复制页面
const copyTab = (page: any) => {
  if (pageFormRef.value) pageFormRef.value.resetFields();
  pageForm.value.pageName = `${page.pageName}_副本`;
  pageForm.value.configList = deepClone(page.configList);
  showAddPageDialog.value = true;
};

// 保存自定义页面
const savePage = () => {
  pageFormRef.value.validate(async (valid: any) => {
    if (valid) {
      if (!pageForm.value.uid) {
        let uid = createPage({
          pageType: "CustomPage",
          ...pageForm.value,
        });
        currentPage.value = uid;
      } else {
        let pageIndex = templateConfig.value.findIndex(
          (item) => item.uid === pageForm.value.uid
        );
        templateConfig.value[pageIndex].pageName = pageForm.value.pageName;
      }
      showAddPageDialog.value = false;
    }
  });
};

// 删除页面
const removeTab = (page: any) => {
  let { uid } = page;
  let pageConfig = templateConfig.value.find((item) => item.uid === uid);
  ElMessageBox.confirm(`是否删除页面【${pageConfig.pageName}】`, "提示", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
  }).then(async () => {
    deletePage(pageConfig.pageType, pageConfig.uid);
    if (currentPage.value === uid) {
      currentPage.value = templateConfig.value[0].uid;
    }
    ElMessage.success("删除成功");
  });
};

// 切换页面
const tabChange = (name: any) => {
  toUpdateIframeMessage();
};

// 新建页面
const createPage = (page: any, config: Array<any> = []) => {
  let { pageType, pageName, link, configList } = page;
  let pageConfig = templateConfig.value.find(
    (item) => item.pageType === pageType
  );
  if (pageName !== "CustomPage" && pageConfig) return page.uid || "";
  else {
    if (config && config instanceof Array === false)
      throw new Error("初始化配置应传入数组类型");
    let pageUid = newRandomUid();
    if (configList) {
      // 复制或引用页面
      templateConfig.value.push({
        pageType,
        pageName,
        uid: pageUid,
        configList: link
          ? configList.map((item: any) => {
            if (item.pageConfig.$pageFlag) {
              return {
                ...item,
                uid: newRandomUid(),
                link: `${link}_${item.uid}`,
              };
            }
            return item;
          })
          : configList.map((item: any) => {
            if (item.pageConfig.$pageFlag) {
              return {
                ...item,
                pageConfig: {
                  ...item.pageConfig,
                  $pageFlag: `${item.type}-${newRandomUid()}`,
                },
              };
            }
            return item;
          }),
      });
    } else {
      templateConfig.value.push({
        pageType,
        pageName,
        uid: pageUid,
        configList: [
          {
            uid: newRandomUid(),
            type: "Background",
            name: "页面背景",
            pageConfig: {},
          },
          ...config,
        ],
      });
    }
    return pageUid;
  }
};

// 删除页面
const deletePage = (pageType: string, uid?: string) => {
  if (!pageType) throw new Error("缺少页面标识");
  let pageIndex = templateConfig.value.findIndex(
    (page) => page.pageType === pageType && (uid ? page.uid === uid : true)
  );
  if (pageIndex >= 0) {
    templateConfig.value.splice(pageIndex, 1);
  }
};

const handleMessage = async (event: any) => {
  var data = event.data;
  console.log("商户端接收到消息：", deepClone(data));
  switch (data.method) {
    case "pageOk":
      iframeReady.value = true;
      break;
    case "configUpdate":
      templateConfig.value[tabIndex.value].configList = data.params;
      break;
    case "templateOk":
      {
        templateConfig.value = data.params.templateConfig;
        templateConfig.value.forEach((item) => {
          if (!item.uid) item.uid = newRandomUid();
          if (item.configList.length == 0) {
            initPageConfig(item);
          }
        });
        currentPage.value = templateConfig.value[0].uid
      }
      templateReady.value = true;
      break;
    case "save":
      try {
        const config = await save();
        window.parent.postMessage(
          {
            method: "save",
            params: config,
          },
          "*"
        );
      } catch (e) { }
      break;
    case "configDelete":
      templateRef.value[tabIndex.value].delete(data.params);
      break;
    case "jumpTo":
      templateRef.value[tabIndex.value].jumpTo(data.params);
      break;
    case "generateCoverOk":
      updatePoster(data.params);
      break;
    default:
      break;
  }
};

const generatePoster = () => {
  iframe.value.contentWindow.postMessage(
    {
      method: "generateCover",
    },
    "*"
  );
};

const save = () => {
  return new Promise(async (resolve, reject) => {
    try {
      let _templateConfig = deepClone(templateConfig.value);
      for (let i = 0; i < templateRef.value.length; i++) {
        _templateConfig[i].configList = await templateRef.value[i].submit();
        _templateConfig[i].configList.forEach((item: any) => {
          if (item.type === "Popup" || item.pageConfig.$mode === "popup") {
            item.pageConfig.$show = false;
          }
        });
      }
      resolve(deepClone(_templateConfig));
    } catch (e) {
      ElNotification.error({
        message: e || "请检查配置项",
      } as any);
    }
  });
};

// 收起展开
const onExpand = (index: number) => {
  currentComponentList.value.components[index].fold = !currentComponentList.value.components[index].fold;
};

// 撤销操作
const undo = () => {
  iframe.value.contentWindow.postMessage(
    {
      method: "configUndo",
      pageName: currentPage.value,
    },
    "*"
  );
};

// 恢复操作
const restore = () => {
  iframe.value.contentWindow.postMessage(
    {
      method: "configRestore",
      pageName: currentPage.value,
    },
    "*"
  );
};

// 编辑组件配置
const editComponent = (val?: any) => {
  if (val) {
    importConfigForm.value = val;
  }
  importConfigDialog.value = true;
};

// 刷新我的组件
const getMyComponent = () => {
  myComponentRef.value.refresh();
};

provide("createPage", createPage);
provide("deletePage", deletePage);
provide("customPageList", customPageList);

onMounted(async () => {
  window.addEventListener("message", handleMessage, false);
  window.parent.postMessage(
    {
      method: "webpackOk",
    },
    "*"
  );
});

onBeforeUnmount(() => {
  window.removeEventListener("message", handleMessage, false);
});

defineExpose({ save, generatePoster });
</script>
<template>
  <div class="templ-container">
    <div class="component-list">
      <div class="component-group" v-for="(group, gIndex) in componentList">
        <div class="component-group_title">
          <span>{{ group.name }}</span>
          <el-button color="#999999" link @click="onExpand(gIndex)">{{
            group.fold ? "展开" : "收起"
          }}</el-button>
        </div>
        <Transition name="expand">
          <div v-show="!group.fold" class="component-group_el">
            <template v-for="item in group.components">
              <div v-if="item.type" class="component-group_el-item" @click="addComponent(item)">
                <img :src="item.icon" alt="" />
                <div>{{ item.name }}</div>
              </div>
            </template>
          </div>
        </Transition>
      </div>
      <!-- 我的组件，sass 平台调用会触发登录 -->
      <MyComponets 
        v-if="from !== 'sass'"
        ref="myComponentRef" 
        @edit="editComponent" 
        @add="addComponent" 
      />
    </div>
    <div class="phone-container">
      <div class="toolbar">
        <div>
          <el-button link title="撤销" @click="undo">
            <svg t="1673234579559" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="15141" width="20" height="20">
              <path
                d="M502.26 289.06c-0.02 16.95 13.26 30.94 30.18 31.8 123.47 8.79 236.97 70.94 310.89 170.21 73.92 99.28 100.91 225.84 73.93 346.65-41.65-181.74-195.38-316.12-381.05-333.08-8.89-0.6-17.63 2.55-24.09 8.7a31.798 31.798 0 0 0-9.86 23.64v85.15a32.343 32.343 0 0 1-50.67 26.41L114.21 413.02a32.341 32.341 0 0 1-14.46-26.95c0-10.84 5.43-20.96 14.46-26.95L451.6 124.68a32.358 32.358 0 0 1 33.28-2.03 32.355 32.355 0 0 1 17.39 28.44v137.97h-0.01z"
                fill="#bfbfbf" p-id="15142"></path>
            </svg>
          </el-button>
          <el-button link title="恢复" @click="restore">
            <svg t="1673234360734" class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg"
              p-id="4965" width="25" height="25">
              <path
                d="M512 371.2V261.973333a25.6 25.6 0 0 1 40.106667-20.906666L819.2 426.666667a25.6 25.6 0 0 1 0 42.666666l-267.093333 186.453334a25.6 25.6 0 0 1-40.106667-20.906667V567.466667a25.173333 25.173333 0 0 0-26.88-25.6 341.333333 341.333333 0 0 0-301.653333 263.68 336.64 336.64 0 0 1 304.64-409.173334 25.173333 25.173333 0 0 0 23.893333-25.173333z"
                fill="#bfbfbf" p-id="4966"></path>
            </svg>
          </el-button>
          <!-- <el-button link title="新增页面" @click="tabAdd"
            ><el-icon color="#bfbfbf" :size="18"><CirclePlusFilled /></el-icon
          ></el-button> -->
        </div>
        <el-tabs v-model="currentPage" type="card" @tab-change="tabChange">
          <el-tab-pane v-for="item in templateConfig" :key="item.uid" :label="item.pageName" :name="item.uid">
            <!-- <template #label>
              <div class="flex-container">
                <span>{{ item.pageName }}</span>
                <el-popover
                  placement="bottom"
                  :width="120"
                  trigger="hover"
                  :show-arrow="false"
                  popper-class="right-menu_popover"
                >
                  <template #reference>
                    <el-icon style="margin-left: 3px"><MoreFilled /></el-icon>
                  </template>
                  <el-button
                    v-if="item.pageType === 'CustomPage'"
                    plain
                    @click.stop="editTab(item)"
                    >编辑</el-button
                  >
                  <el-button plain @click.stop="copyTab(item)">复制</el-button>
                  <el-button
                    v-if="
                      pageTypeList.find(
                        (page) => page.pageType === item.pageType
                      )?.removeable === true
                    "
                    plain
                    @click.stop="removeTab(item)"
                    >删除</el-button
                  >
                </el-popover>
              </div>
            </template> -->
          </el-tab-pane>
        </el-tabs>
      </div>

      <div class="phone" v-loading="iframeLoading">
        <iframe v-show="!iframeLoading" ref="iframe" class="iframe" :src="`${iframeUrl}#/design?original=saas`"
          frameborder="0"></iframe>
      </div>
    </div>
    <div class="tabs-container">
      <template v-for="(config, index) in templateConfig">
        <div style="height: 100%" v-show="currentPage === config.uid">
          <SetTemplate :ref="(el) => {
            if (el) templateRef[index] = el;
          }
            " :original="original" v-model:model-value="config.configList" :pageList="templateConfig"
            @change="toUpdateIframeMessage" @refresh="getMyComponent"></SetTemplate>
        </div>
      </template>
    </div>
  </div>
  <Dialog v-model="showAddPageDialog" title="页面配置" :width="500" @confirm="savePage">
    <el-form ref="pageFormRef" :model="pageForm" label-width="auto">
      <el-form-item label="页面名称" prop="pageName" :rules="[
        { required: true, message: '请填写页面名称', trigger: 'blur' },
        { max: 10, message: '页面名称不能超过10个字符', trigger: 'blur' },
      ]">
        <el-input v-model="pageForm.pageName" clearable placeholder="请输入页面名称"></el-input>
      </el-form-item>
      <!-- 新建引用页面 -->
      <el-form-item v-if="pageForm.configList && !pageForm.uid" label="关联数据" prop="link">
        <el-select v-model="pageForm.link" placeholder="请选择" style="width: 200px" clearable>
          <template v-for="page in templateConfig" :key="page.uid"><el-option v-if="page.uid !== pageForm.uid"
              :label="page.pageName" :value="page.uid" />
          </template>
        </el-select>
      </el-form-item>
    </el-form>
  </Dialog>
  <!-- 组件导入 -->
  <ImportComponentsDialog v-model:form="importConfigForm" v-model:show="importConfigDialog" @save="getMyComponent" />
</template>
<style lang="scss" scoped>
.templ-container {
  display: flex;
  justify-content: space-between;
  background-color: #ffffff;
  height: 100vh;

  .component-list {
    width: 30%;
    max-width: 340px;
    height: 100%;
    overflow: auto;

    .component-group_title {
      padding: 8px 12px;
      background-color: #f7f7fa;
      display: flex;
      justify-content: space-between;
    }

    .component-group_el {
      display: flex;
      align-items: center;
      flex-wrap: wrap;
      padding: 10px;

      &-item {
        width: 76px;
        height: 76px;
        border: 1px solid transparent;
        border-radius: 5px;
        display: flex;
        flex-direction: column;
        justify-content: space-around;
        align-items: center;
        font-size: 14px;
        cursor: pointer;
        text-align: center;
        white-space: nowrap;
        overflow: hidden;
        text-overflow: ellipsis;

        img {
          display: block;
          width: 38px;
          height: 57px;
          object-fit: contain;
        }

        &:hover {
          border-color: #fb6638;
        }
      }
    }
  }
}

.phone-container {
  margin: 0 40px;
  align-self: center;

  .toolbar {

    // display: flex;
    // justify-content: space-between;
    // align-items: center;
    .toolbar-item {
      font-size: 12px;
      cursor: pointer;
    }
  }

  :deep(.el-tabs) {
    max-width: 330px;

    .el-tabs__content {
      padding: 0;
    }

    .el-tabs__header {
      margin-bottom: 0;
    }
  }

  .phone {
    width: 332px;
    height: 627px;
    border: 1px solid #efefef;
    position: relative;
    box-sizing: border-box;

    .iframe {
      width: 100%;
      height: 100%;
    }
  }
}

.tabs-container {
  flex: 1;
  height: 100%;
  overflow: auto;

  :deep(.config-container) {
    height: 100%;
    overflow-x: hidden;
    overflow-y: auto;
  }
}

.expand-enter-from {
  height: 0;
}

.expand-enter-to {
  height: auto;
}

.expand-leave-to {
  height: 0;
}

.flex-container {
  display: flex;
  align-items: center;
}
</style>
